<template>
  <div class="admin-container">
    <h2>管理员后台</h2>
    <div class="admin-tabs">
      <button
          v-for="tab in tabs"
          :key="tab.id"
          :class="{ active: activeTab === tab.id }"
          @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>

    <div class="tab-content">
      <!-- 商品管理 -->
      <div v-if="activeTab === 'products'" class="product-management">
        <h3>商品管理</h3>
        <button class="add-product-btn" @click="showAddProductModal = true">
          添加新商品
        </button>
        <div class="product-list">
          <div v-for="product in products" :key="product.id" class="product-item">
            <img :src="product.image" :alt="product.name" class="product-image">
            <div class="product-details">
              <h4>{{ product.name }}</h4>
              <p>¥{{ product.price }}</p>
              <p>库存: {{ product.stock }}</p>
            </div>
            <div class="product-actions">
              <button @click="editProduct(product)">编辑</button>
              <button @click="deleteProduct(product.id)">删除</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单管理 -->
      <div v-if="activeTab === 'orders'" class="order-management">
        <h3>订单管理</h3>
        <div class="order-list">
          <div v-for="order in allOrders" :key="order.id" class="order-item">
            <div class="order-header">
              <span>订单 #{{ order.id }}</span>
              <span>{{ formatDate(order.createdAt) }}</span>
              <span>用户ID: {{ order.userId }}</span>
              <span>总价: ¥{{ order.total.toFixed(2) }}</span>
              <select v-model="order.status" @change="updateOrderStatus(order)">
                <option value="processing">处理中</option>
                <option value="completed">已完成</option>
                <option value="cancelled">已取消</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户管理 -->
      <div v-if="activeTab === 'users'" class="user-management">
        <h3>用户管理</h3>
        <div class="user-list">
          <div v-for="user in users" :key="user.id" class="user-item">
            <span>{{ user.username }}</span>
            <span>{{ user.isAdmin ? '管理员' : '普通用户' }}</span>
            <button @click="toggleAdminStatus(user)">
              {{ user.isAdmin ? '取消管理员' : '设为管理员' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑商品模态框 -->
    <div v-if="showAddProductModal" class="modal">
      <div class="modal-content">
        <h3>{{ editingProduct ? '编辑商品' : '添加新商品' }}</h3>
        <form @submit.prevent="saveProduct">
          <div class="form-group">
            <label>商品名称</label>
            <input v-model="productForm.name" required>
          </div>
          <div class="form-group">
            <label>价格</label>
            <input v-model="productForm.price" type="number" min="0" required>
          </div>
          <div class="form-group">
            <label>库存</label>
            <input v-model="productForm.stock" type="number" min="0" required>
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="productForm.description" required></textarea>
          </div>
          <div class="form-group">
            <label>图片URL</label>
            <input v-model="productForm.image" required>
          </div>
          <div class="form-group">
            <label>商品分类</label>
            <select v-model="productForm.category" class="form-control" required>
              <option v-for="category in categories" :key="category.id" :value="category.slug">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="form-actions">
            <button type="button" @click="cancelEdit">取消</button>
            <button type="submit">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import {
  fetchProducts,
  addProduct,
  updateProduct,
  deleteProduct as apiDeleteProduct,
  fetchAllOrders,
  updateOrder as apiUpdateOrder,
  users,
  categories
} from '../api/mockData'

export default {
  setup() {
    const tabs = [
      { id: 'products', name: '商品管理' },
      { id: 'orders', name: '订单管理' },
      { id: 'users', name: '用户管理' }
    ]
    const activeTab = ref('products')
    const products = ref([])
    const allOrders = ref([])
    const showAddProductModal = ref(false)
    const editingProduct = ref(null)
    const productForm = ref({
      name: '',
      price: 0,
      stock: 0,
      description: '',
      image: '',
      category: 'electronics' // 默认选择电子产品分类
    })

    onMounted(async () => {
      products.value = await fetchProducts()
      allOrders.value = await fetchAllOrders()
    })

    const formatDate = (dateString) => {
      const options = { year: 'numeric', month: 'long', day: 'numeric' }
      return new Date(dateString).toLocaleDateString(undefined, options)
    }

    const editProduct = (product) => {
      editingProduct.value = product
      productForm.value = { ...product }
      showAddProductModal.value = true
    }

    const cancelEdit = () => {
      showAddProductModal.value = false
      editingProduct.value = null
      productForm.value = {
        name: '',
        price: 0,
        stock: 0,
        description: '',
        image: ''
      }
    }

    const saveProduct = async () => {
      try {
        if (editingProduct.value) {
          // 更新商品
          const updatedProduct = await updateProduct({
            ...productForm.value,
            id: editingProduct.value.id
          })
          const index = products.value.findIndex(p => p.id === updatedProduct.id)
          if (index !== -1) {
            products.value.splice(index, 1, updatedProduct)
          }
        } else {
          // 添加新商品
          const newProduct = await addProduct(productForm.value)
          products.value.push(newProduct)
        }
        cancelEdit()
      } catch (error) {
        alert('保存失败: ' + error.message)
      }
    }

    const deleteProduct = async (id) => {
      if (confirm('确定要删除这个商品吗？')) {
        try {
          await apiDeleteProduct(id)
          products.value = products.value.filter(p => p.id !== id)
        } catch (error) {
          alert('删除失败: ' + error.message)
        }
      }
    }

    const updateOrderStatus = async (order) => {
      try {
        await apiUpdateOrder(order.id, { status: order.status })
      } catch (error) {
        alert('更新订单状态失败: ' + error.message)
      }
    }

    const toggleAdminStatus = (user) => {
      user.isAdmin = !user.isAdmin
      // 在实际应用中，这里应该调用API更新用户权限
    }

    return {
      tabs,
      activeTab,
      products,
      allOrders,
      users,
      showAddProductModal,
      editingProduct,
      productForm,
      formatDate,
      editProduct,
      cancelEdit,
      saveProduct,
      deleteProduct,
      updateOrderStatus,
      toggleAdminStatus
    }
  }
}
</script>

<style scoped>
.admin-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1rem;
}
.admin-tabs {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 1rem;
}
.admin-tabs button {
  padding: 0.5rem 1rem;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1rem;
  border-bottom: 2px solid transparent;
}
.admin-tabs button.active {
  border-bottom: 2px solid #42b983;
  font-weight: bold;
}
.tab-content {
  padding: 1rem;
}

/* 商品管理样式 */
.product-management {
  margin-top: 1rem;
}
.add-product-btn {
  padding: 0.5rem 1rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  margin-bottom: 1rem;
  cursor: pointer;
}
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}
.product-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  gap: 1rem;
}
.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}
.product-details {
  flex: 1;
}
.product-details h4 {
  margin: 0;
}
.product-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.product-actions button {
  padding: 0.3rem 0.5rem;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}
.product-actions button:hover {
  background: #f5f5f5;
}

/* 订单管理样式 */
.order-management {
  margin-top: 1rem;
}
.order-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.order-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1rem;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}
.order-header select {
  padding: 0.3rem;
  border-radius: 4px;
  border: 1px solid #ddd;
}

/* 用户管理样式 */
.user-management {
  margin-top: 1rem;
}
.user-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border: 1px solid #eee;
  border-radius: 8px;
}
.user-item button {
  padding: 0.3rem 0.5rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal-content {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
}
.modal-content h3 {
  margin-top: 0;
}
.form-group {
  margin-bottom: 1rem;
}
.form-group label {
  display: block;
  margin-bottom: 0.5rem;
}
.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.form-group textarea {
  height: 100px;
}
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}
.form-actions button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.form-actions button[type="button"] {
  background: #f0f0f0;
}
.form-actions button[type="submit"] {
  background: #42b983;
  color: white;
}
</style>
